package com.jia.leetCode;

import java.util.Arrays;

public class Pro0211 {
    public static void main(String[] args) {
        Pro0211 pro0211 = new Pro0211();
        pro0211.addWord("bad");
        pro0211.addWord("dad");
        pro0211.addWord("mad");
        //"pad"],["bad"],[".ad"],["b.."
        System.out.println(pro0211.search("pad"));;
        System.out.println(pro0211.search("bad"));;
        System.out.println(pro0211.search(".ad"));;
        System.out.println(pro0211.search("b.."));;
    }

    class TrieNode {
        TrieNode[] links;
        final int R = 26;
        boolean isEnd;
        public TrieNode(){links = new TrieNode[R];}

        @Override
        public String toString() {
            return "TrieNode{" +
                    "links=" + Arrays.toString(links) +
                    ", R=" + R +
                    ", isEnd=" + isEnd +
                    '}';
        }
    }

    private TrieNode root;

    /** Initialize your data structure here. */
    public Pro0211() {
        this.root = new TrieNode();
    }

    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode node = this.root;
        for(int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if(node.links[c-'a']==null) {
                node.links[c-'a'] = new TrieNode();
            }
            node = node.links[c-'a'];
        }
        node.isEnd = true;
    }

    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    public boolean search(String word) {
        return search(this.root, word, 0);
    }
    private boolean search(TrieNode node, String word, int index) {
        if(index < word.length() && node != null && node.links != null) {
            char c = word.charAt(index);
            if(index == (word.length()-1)) return node.links[c - 'a'].isEnd;
            if(c == '.') {
                for(TrieNode n : node.links) {
                    if(search(n, word, index + 1)) {
                        return true;
                    }
                }
            }else {
                return search(node.links[c-'a'], word, index + 1);
            }
        }
        return false;
    }
}
